//
//  BKUserBindingViewController.m
//  bestkeep
//
//  Created by windCould on 16/11/28.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserBindingViewController.h"
#import "BKCustextFieldView.h"
#import "BKMyCommon.h"
#import "BKUserCodeFormat.h"
#import "BKUserUnitRequestAPI.h"
#import "Sign.h"
#import "BKUserRegisterViewController.h"
#import "BKUserFindPwdViewController.h"
@interface BKUserBindingViewController ()<UITextFieldDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)UILabel * tipLab;
@property (nonatomic,strong)BKCustextFieldView * accountTextField;
@property (nonatomic,strong)BKCustextFieldView * passwordTexField;
@property (nonatomic,strong)BKCustextFieldView * imgCodeTexField;
@property (nonatomic,strong)UIButton * bingdinAndLoginBtn;



@end

@implementation BKUserBindingViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"绑定登录";
    [self setUpViews];
}

#pragma mark =========================Function================================

-(void)goToBindinAndLoginBtnClick
{
    [self.view  endEditing:YES];
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:self.accountTextField.textField.text]) {
        
        NSLog(@"请输入你的账户。。。。 ");
        [HUD showErrorMessage:@"请输入手机号码"];
        return;
    }
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:self.passwordTexField.textField.text]) {
        
        NSLog(@"请输入密码。。。。。。。");
        [HUD showErrorMessage:@"请输入密码"];
        return;
    }
    
    NSString *openType = [self.infoDict objectForKey:@"open_type"];
    NSString *openId;
    NSString *deviceType = @"10";
    NSString *accessToken;
    NSString *appId = [openType isEqualToString:@"1"] ? QQ_APPID:WX_APPID;
    accessToken = self.infoDict[@"access_token"];
    openId = self.infoDict[@"open_id"];
    NSString *time = [Sign getSystemTime];
    NSDictionary *dict = @{@"username":_accountTextField.textField.text,
                           @"password":_passwordTexField.textField.text,
                           @"openId":openId,
                           @"openType":openType,
                           @"deviceType":deviceType,
                           @"accessToken":accessToken,
                           @"appId":appId
                           };
    NSString *sign = [Sign sign:dict time:time];
    
    NSDictionary *dictS = @{@"username":_accountTextField.textField.text,
                            @"password":_passwordTexField.textField.text,
                            @"openId":openId,
                            @"openType":openType,
                            @"deviceType":deviceType,
                            @"accessToken":accessToken,
                            @"sign":sign,
                            @"time":time,
                            @"appId":appId
                            };
    [BKIndicationView dismiss];
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI bindOpenAccount:dictS mycallBack:^(id obj, NSError *error) {
        [BKIndicationView  dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                //[HUD showSuccessMessage:@"绑定成功"];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter]postNotificationName:NSNotificationBKUserRelogin object:nil];
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                
                NSString * msgStr = result.msg;
                
                if([msgStr rangeOfString:@"注册"].location != NSNotFound){
                    
                    if (IOS8) {
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msgStr preferredStyle:  UIAlertControllerStyleAlert];
                        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
                        UIAlertAction *registerAction = [UIAlertAction actionWithTitle:@"去注册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            
                            BKUserRegisterViewController *regisetrC = [[BKUserRegisterViewController alloc]init];
                            [self.navigationController pushViewController:regisetrC animated:YES];
                        }];
                        
                        [alert addAction:cancleAction];
                        [alert addAction:registerAction];
                        [self presentViewController:alert animated:YES completion:nil];
                        return ;
                    }
                    else
                    {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msgStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去注册", nil];
                        alert.tag = 1000;
                        [alert show];
                        return;
                    }
                    
                }
                
                
                if ([msgStr rangeOfString:@"密码错误"].location != NSNotFound) {
                    
                    if (IOS8) {
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msgStr preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                        UIAlertAction *passWordAction = [UIAlertAction actionWithTitle:@"找回密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            
                            BKUserFindPwdViewController *findPwdVC = [[BKUserFindPwdViewController alloc]init];
                            
                            [self.navigationController pushViewController:findPwdVC animated:YES];
                        }];
                        [alert addAction:cancleAction];
                        [alert addAction:passWordAction];
                        [self presentViewController:alert animated:YES completion:nil];
                        return;
                    }
                    else
                    {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msgStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"找回密码", nil];
                        alert.tag = 1001;
                        [alert show];
                        return;
                    }
                    
                }
                
              //  if ([msgStr rangeOfString:@"绑定"].location != NSNotFound) {
                    
              //      NSLog(@"绑定成功");
              //      [HUD showSuccessMessage:@"绑定成功"];
              //  }
                
               [HUD showErrorMessage:result.msg];
            }
        
        
            NSLog(@"%@---",obj);
        }
    }];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        
        if (buttonIndex == 0) {
            
            return;
        }
        if (buttonIndex == 1) {
            
            BKUserFindPwdViewController *findPwdVC = [[BKUserFindPwdViewController alloc]init];
            
            [self.navigationController pushViewController:findPwdVC animated:YES];

        }
        
    }
    
    if (alertView.tag == 1001) {
        
        if (buttonIndex == 0) {
            
            return;
        }
        if (buttonIndex == 1) {
            
            BKUserFindPwdViewController *findPwdVC = [[BKUserFindPwdViewController alloc]init];
            
            [self.navigationController pushViewController:findPwdVC animated:YES];

        }
    }
    
    
}

#pragma mark =========================布局===================================

-(void)setUpViews
{
    _tipLab =[[UILabel alloc]initWithFrame:CGRectZero];
    _tipLab.font = [UIFont systemFontOfSize:12];
    _tipLab.textColor=HexColor(0x888888);
    _tipLab.text=@"关联已有BESTKEEP手机账号，关联后可以用QQ/微信登录";
    [self.view addSubview:_tipLab];
    
    _accountTextField = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewDefultType];
    _accountTextField.placeHolderString = @"请输入手机号";
    _accountTextField.imgUrlStr = @"BK_My_butter_icon_02";
    _accountTextField.textField.delegate = self;
    _accountTextField.textField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_accountTextField];
    
    _passwordTexField = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewDefultType];
    _passwordTexField.placeHolderString = @"请输入密码";
    _passwordTexField.textField.secureTextEntry = YES;
    _passwordTexField.imgUrlStr = @"BK_My_butter_icon_03";
    _passwordTexField.textField.delegate = self;
    [self.view addSubview:_passwordTexField];
    
    //    _imgCodeTexField = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewImageCodeType];
    //    _imgCodeTexField.placeHolderString = @"请输入图片验证码";
    //    _imgCodeTexField.imgUrlStr = @"";
    //    [self.view addSubview:_imgCodeTexField];
    
    _bingdinAndLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _bingdinAndLoginBtn.titleLabel.font = UIFontBoldCustom(18);
    [_bingdinAndLoginBtn setTitle:@"绑定并登录" forState:UIControlStateNormal];
    _bingdinAndLoginBtn.layer.cornerRadius = 4;
    _bingdinAndLoginBtn.layer.masksToBounds = YES;
    [_bingdinAndLoginBtn addTarget:self action:@selector(goToBindinAndLoginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _bingdinAndLoginBtn.backgroundColor = BK_MY_COLOR_01;
    [self.view addSubview:_bingdinAndLoginBtn];
    
    [self layoutviews];
}

-(void)layoutviews
{
    [_tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@(27));
    }];
    
    [_accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_tipLab.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@(50));
    }];
    
    [_passwordTexField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_accountTextField.mas_bottom).offset(0);
        make.left.mas_equalTo(_accountTextField.mas_left).offset(0);
        make.right.mas_equalTo(_accountTextField.mas_right).offset(0);
        make.height.mas_equalTo(@(50));
    }];
    
    //    [_imgCodeTexField mas_makeConstraints:^(MASConstraintMaker *make) {
    //
    //        make.top.mas_equalTo(_passwordTexField.mas_bottom).offset(0);
    //        make.left.mas_equalTo(_passwordTexField.mas_left).offset(0);
    //        make.right.mas_equalTo(_passwordTexField.mas_right).offset(0);
    //        make.height.mas_equalTo(@(50));
    //    }];
    
    [_bingdinAndLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_passwordTexField.mas_bottom).offset(20);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@(45));
    }];
    
    
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

@end
